import 'dart:convert';
import 'dart:io';

import 'package:ecy_app_flutter/ecycommon/EcyEnvironment.dart';
import 'package:ecy_app_flutter/main.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_styled_toast/flutter_styled_toast.dart';
import 'package:flutter_update_dialog/update_dialog.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../../EcyRouter.dart';
import '../../../constant/EcyEventConsnt.dart';
import '../../../ecycommon/EcyCommonWidgets.dart';
import '../../../ecycommon/EcyEventBus.dart';
import '../../../ecycommon/EcyRequestBaseManager.dart';
import '../../../ecycommon/utils/EcyUserUtil.dart';
import '../../../model/EcyApiCommonResponse.dart';
import '../../mainTabPage.dart';

class EcyMySettingPage extends EcyCommonBaseWidget {
  EcyMySettingPage({required super.key});

  @override
  _EcyMySettingPageState createState() {
    return _EcyMySettingPageState(this);
  }
}

class _EcyMySettingPageState extends EcyCommonBaseWidgetState {
  late EcyCommonBaseWidget controller;
  late String? version = "1.0";
  late bool needUpdate = false;
  late UpdateDialog? dialog;
  late Map<String, dynamic>? lastest;

  _EcyMySettingPageState(EcyCommonBaseWidget vc) {
    controller = vc;
  }

  @override
  void initState() {
    super.initState();
    getVersion();
  }

  void getVersion() async {
    var response = await EcyRequestbasemanager().get(
        "/app/api/app/commons/version", {"type": Platform.isIOS ? "2" : "1"});
    if (response != null) {
      var commonResponse =
          EcyApiCommonResponse.fromJson(response, (response) => json);
      if (commonResponse.code == 0 || commonResponse.code == 200) {
        PackageInfo packageInfo = await PackageInfo.fromPlatform();
        String _version = packageInfo.version;
        Map<String, dynamic> _lastest = response["data"];
        bool u = true;
        try {
          u = int.parse(packageInfo.version.replaceAll(".", "")) >= int.parse(_lastest["versionCode"].replaceAll(".", ""));
        } catch (e) {
          u = true;
        }
        setState(() {
          version = _version;
          needUpdate = !u;
          lastest = _lastest;
        });
      }
    }
  }

  // void checkUpdate() async {
  //   const packageName = 'my_package';
  //   const currentVersion = '0.1.0';
  //
  //   // Initialize an instance of PubUpdater.
  //   final pubUpdater = PubUpdater();
  //
  //   // Check whether a package is up to date.
  //   final isUpToDate = await pubUpdater.isUpToDate(
  //     packageName: packageName,
  //     currentVersion: currentVersion,
  //   );
  //
  //   if (!isUpToDate) {
  //     // Upgrade to the latest version if not up to date.
  //     await pubUpdater.update(packageName: packageName);
  //   }
  //
  //   // You can also query the latest version available for a specific package.
  //   final latestVersion = await pubUpdater.getLatestVersion(packageName);
  // }

  // 弹出对话框
  Future<bool?> showConfirmDialog(String content, {int type = 0}) {
    return showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          // title: const Text(''),
          contentPadding: const EdgeInsets.all(0),
          backgroundColor: Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8.0),
          ),
          content: SizedBox(
            height: 130,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Padding(
                  padding: const EdgeInsets.only(top: 20, bottom: 30),
                  child: Text(
                    content,
                    style: TextStyle(fontSize: 18),
                  ),
                ),
                const Divider(height: 0, color: Color(0XFFdcdcdc)),
                SizedBox(
                  height: 50,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Expanded(
                        flex: 1,
                        child: DecoratedBox(
                          decoration: const BoxDecoration(
                              border: Border(
                            right: BorderSide(
                              width: 1.0,
                              color: Color(0XFFdcdcdc),
                            ),
                          )),
                          child: TextButton(
                            style: const ButtonStyle(
                              alignment: Alignment.center,
                            ),
                            child: Text(
                              '取消',
                              style: const TextStyle(
                                  fontSize: 18, color: Colors.black),
                            ),
                            onPressed: () =>
                                Navigator.of(context).pop(), // 关闭对话框
                          ),
                        ),
                      ),
                      Expanded(
                        flex: 1,
                        child: TextButton(
                          child: Text(
                            type == 0 ? '确定' : '退出',
                            style: const TextStyle(
                                fontSize: 18, color: Color(0xFFEA4B9B)),
                          ),
                          onPressed: () {
                            //关闭对话框并返回true
                            Navigator.of(context).pop(true);
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          actionsAlignment: MainAxisAlignment.spaceAround,
          actionsPadding: const EdgeInsets.all(0),
        );
      },
    );
  }

  void showUpdaterAlert() {
    if (needUpdate) {
      dialog = UpdateDialog.showUpdate(context,
          title: lastest?["versionTitle"] ?? ("版本升级" + lastest?["versionCode"]),
          updateContent: lastest?["versionContent"] ?? "", onUpdate: () {
        launchAppStore();
      });
    }
  }

  Future<void> launchAppStore() async {
    const appStoreUrl = 'itms-apps://itunes.apple.com/app/id6741015928'; // iOS
    const playStoreUrl =
        'market://details?id=com.ecy.app.ecy_app_flutter'; // Android
    final url = Platform.isIOS ? appStoreUrl : playStoreUrl;
    if (Platform.isIOS) {
      if (await canLaunchUrl(Uri.parse(url))) {
        await launchUrl(Uri.parse(url));
      } else {
        const webUrl = 'https://www.goodsqi.com/h5/html/download.html';
        final url2 = Platform.isIOS
            ? (lastest?["iosUrl"] ?? webUrl)
            : (lastest?["apkUrl"] ?? webUrl);
        // 无法打开应用商店，跳转到网页版
        await launchUrl(Uri.parse(url2));
      }
    } else {
      await launchUrl(
          Uri.parse((lastest?["apkUrl"]) ?? "https://www.pgyer.com/VBS0GMTT"));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFFF5F5F5),
      appBar: AppBar(
        backgroundColor: Colors.white,
        leadingWidth: 50.w,
        leading: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            EcyRouter.pop(context, "");
          },
          child: Align(
            alignment: Alignment.centerRight,
            child: Image.asset(
              "assets/images/ic_back.png",
              width: 30.w,
            ),
          ),
        ),
        titleSpacing: 0,
        centerTitle: true,
        title: Text("设置",
            style: TextStyle(
                fontFamily: "PingFang SC",
                fontWeight: FontWeight.w700,
                fontSize: 16.sp,
                color: const Color(0xFF262626))),
      ),
      body: Padding(
          padding: const EdgeInsets.all(10),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Padding(
                  padding: const EdgeInsets.only(left: 15, bottom: 10),
                  child: Text(
                    '个人',
                    style: TextStyle(
                        fontFamily: "PingFang SC",
                        fontWeight: FontWeight.w500,
                        fontSize: 14.sp,
                        color: const Color(0xFF595959)),
                  )),
              Card(
                color: Colors.white,
                elevation: 0,
                margin: const EdgeInsets.only(bottom: 2),
                child: ListTile(
                  title: Text('个人资料',
                      style: TextStyle(
                          fontFamily: "PingFang SC",
                          fontWeight: FontWeight.w700,
                          fontSize: 16.sp,
                          color: const Color(0xFF262626))),
                  trailing: const Icon(Icons.arrow_forward_ios, size: 14),
                  splashColor: Colors.transparent,
                  onTap: () {
                    EcyRouter.pushNoParams(context, EcyRouter.personInfoPage);
                  },
                ),
              ),
              Card(
                color: Colors.white,
                elevation: 0,
                margin: const EdgeInsets.only(bottom: 2),
                child: ListTile(
                  title: Text('账号与安全',
                      style: TextStyle(
                          fontFamily: "PingFang SC",
                          fontWeight: FontWeight.w700,
                          fontSize: 16.sp,
                          color: const Color(0xFF262626))),
                  trailing: const Icon(Icons.arrow_forward_ios, size: 14),
                  splashColor: Colors.transparent,
                  onTap: () {
                    EcyRouter.pushNoParams(
                        context, EcyRouter.accountSecurityPage);
                  },
                ),
              ),
              Padding(
                  padding: const EdgeInsets.only(left: 15, top: 10, bottom: 10),
                  child: Text('通用',
                      style: TextStyle(
                          fontFamily: "PingFang SC",
                          fontWeight: FontWeight.w500,
                          fontSize: 14.sp,
                          color: const Color(0xFF595959)))),
              Card(
                color: Colors.white,
                elevation: 0,
                margin: const EdgeInsets.only(bottom: 2),
                child: ListTile(
                  title: Text('清除缓存',
                      style: TextStyle(
                          fontFamily: "PingFang SC",
                          fontWeight: FontWeight.w700,
                          fontSize: 16.sp,
                          color: const Color(0xFF262626))),
                  trailing: const Icon(
                    Icons.arrow_forward_ios,
                    size: 14,
                  ),
                  splashColor: Colors.transparent,
                  onTap: () async {
                    //弹出对话框并等待其关闭
                    bool? delete =
                        await showConfirmDialog('您确定要清除缓存吗？', type: 0);
                    if (delete != null && delete) {
                      EasyLoading.showToast("缓存清理成功",
                          duration: const Duration(seconds: 1));
                    }
                  },
                ),
              ),
              Card(
                color: Colors.white,
                elevation: 0,
                margin: const EdgeInsets.only(bottom: 2),
                child: ListTile(
                  title: Text('关于有谷气',
                      style: TextStyle(
                          fontFamily: "PingFang SC",
                          fontWeight: FontWeight.w700,
                          fontSize: 16.sp,
                          color: const Color(0xFF262626))),
                  trailing: const Icon(Icons.arrow_forward_ios, size: 14),
                  splashColor: Colors.transparent,
                  onTap: () {
                    EcyRouter.push(context, EcyRouter.aboutGoodsQiPage, null);
                  },
                ),
              ),
              Card(
                color: Colors.white,
                elevation: 0,
                margin: const EdgeInsets.only(bottom: 2),
                child: ListTile(
                  title: Text('版本',
                      style: TextStyle(
                          fontFamily: "PingFang SC",
                          fontWeight: FontWeight.w700,
                          fontSize: 16.sp,
                          color: const Color(0xFF262626))),
                  trailing: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: needUpdate
                        ? [
                            Container(
                              width: 7.w,
                              height: 7.w,
                              padding: const EdgeInsets.all(5),
                              decoration: BoxDecoration(
                                color: Colors.red,
                                borderRadius: BorderRadius.circular(10),
                              ),
                              child: const Text(
                                '',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 12,
                                ),
                                textAlign: TextAlign.center,
                              ),
                            ),
                            Container(
                              padding: const EdgeInsets.all(5),
                              child: Text(
                                version ?? '1.0.0',
                                style: TextStyle(
                                    fontFamily: "PingFang SC",
                                    color: const Color(0xFF8C8C8C),
                                    fontSize: 16.sp,
                                    fontWeight: FontWeight.w500),
                                textAlign: TextAlign.center,
                              ),
                            ),
                            const Icon(Icons.arrow_forward_ios, size: 14)
                          ]
                        : [
                            Container(
                              padding: const EdgeInsets.all(5),
                              child: Text(
                                version ?? '1.0.0',
                                style: TextStyle(
                                    fontFamily: "PingFang SC",
                                    color: const Color(0xFF8C8C8C),
                                    fontSize: 16.sp,
                                    fontWeight: FontWeight.w500),
                                textAlign: TextAlign.center,
                              ),
                            ),
                            const Icon(Icons.arrow_forward_ios, size: 14)
                          ],
                  ),
                  splashColor: Colors.transparent,
                  onTap: () {
                    showUpdaterAlert();
                  },
                ),
              ),
              const Padding(padding: EdgeInsets.only(bottom: 50)),
              Card(
                color: Colors.white,
                elevation: 0,
                margin: const EdgeInsets.only(bottom: 2),
                child: ListTile(
                  title: Align(
                    alignment: Alignment.center, // 设置对齐方式为居中
                    child: Text('退出登录',
                        style: TextStyle(
                            fontFamily: "PingFang SC",
                            fontWeight: FontWeight.w700,
                            fontSize: 16.sp,
                            color: const Color(0xFF262626))),
                  ),
                  onTap: () async {
                    //弹出对话框并等待其关闭
                    bool? delete = await showConfirmDialog('您确定要退出吗？', type: 1);
                    if (delete != null && delete) {
                      EcyUserUtil.clearUserInfo();
                      Navigator.of(context).pushAndRemoveUntil(
                        MaterialPageRoute(
                            builder: (context) => ContainPage(
                                  key: const Key("containPage"),
                                  appLinks: gAppLinks,
                                )),
                        (Route<dynamic> route) => false,
                      );
                      EcyEventBus().emit(EcyEventConst.kLogout);
                      EcyRequestbasemanager().delete("/auth/logout", {});
                    }
                  },
                ),
              ),
            ],
          )),
    );
  }
}
